package com.xilin.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xilin.wiki.domain.Ebook;
import com.xilin.wiki.domain.EbookExample;
import com.xilin.wiki.mapper.EbookMapper;
import com.xilin.wiki.req.EbookQueryReq;
import com.xilin.wiki.req.EbookSaveReq;
import com.xilin.wiki.response.EbookQueryResp;
import com.xilin.wiki.response.PageResp;
import com.xilin.wiki.util.CopyUtil;
import com.xilin.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class EbookService {
    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);
    @Autowired()
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {

        EbookExample ebookExample = new EbookExample();
        //内部类 where查询
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        //判断是否查询单个数据，否则全部展示
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        //查sql获得的<Ebook> list
        List<Ebook> list = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo<>(list);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());
        //List<Ebook> --> List<EbookResp>
        List<EbookQueryResp> respList = new ArrayList<>();

       /* for (Ebook ebook : list) {
          //EbookResp ebookResp = new EbookResp();
          //  BeanUtils.copyProperties(ebook,ebookResp);
          对象复制
            EbookResp ebookResp = CopyUtil.copy(ebook, EbookResp.class);
            respList.add(ebookResp);
        }*/

        //列表复制
        List<EbookQueryResp> list1 = CopyUtil.copyList(list, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list1);
        return pageResp;
    }

    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
